package com.dokimall.cart.controller;

import com.dokimall.cart.interceptor.CartInterceptor;
import com.dokimall.cart.service.CartService;
import com.dokimall.cart.vo.Cart;
import com.dokimall.cart.vo.CartItem;
import com.dokimall.cart.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @ClassName: CartController
 * @Description:
 * @Author
 * @Date 2021/10/24
 * @Version 1.0
 */
@Controller
public class CartController {

    @Autowired
    CartService cartService;

    // 查询购物车选中状态的商品信息
    @ResponseBody
    @GetMapping("/getCheckedItem")
    public List<CartItem> getCheckedItem(){
        return cartService.getCheckedItem();
    }

    // 修改购物车选中状态
    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId")Long skuId,
                            @RequestParam("check")Integer check){
        cartService.checkItem(skuId,check);
        return "redirect:http://cart.dokimall.com/cart.html";
    }

    // 修改购物车中某个商品的数量
    @GetMapping("/countItem")
    public String changeItemNum(@RequestParam("skuId")Long skuId,
                                @RequestParam("num")Integer num){
        cartService.changeItemNum(skuId,num);
        return "redirect:http://cart.dokimall.com/cart.html";
    }

    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId")Long skuId){
        cartService.deleteItem(skuId);
        return "redirect:http://cart.dokimall.com/cart.html";
    }

    @GetMapping("/cart.html")
    public String cartListPage(Model model) throws ExecutionException, InterruptedException {
        UserInfo userInfo = CartInterceptor.threadLocal.get();
        Cart cart = cartService.getCart(userInfo);
        model.addAttribute("cart",cart);
        return "cartList";
    }

    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId")Long skuId,
                            @RequestParam("num")Integer num,
                            RedirectAttributes attributes) throws ExecutionException, InterruptedException {
        System.out.println("skuId"+skuId+"商品数量"+num);
        cartService.addToCart(skuId,num);
        attributes.addAttribute("skuId",skuId);
        return "redirect:http://cart.dokimall.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String addToCartSuccess(@RequestParam("skuId")Long skuId,Model model){
        CartItem cartItem = cartService.getCartById(skuId);
        model.addAttribute("item",cartItem);
        return "success";
    }

}
